import us from '@/api/user'
const state = {
  isLogin: localStorage.getItem('token') ? true : false
}

const mutations = {
  setLoginState(state, b) {
    state.isLogin = b
  }
}

//异步都用actions
const actions = {
  login({
    commit
  }, user) {
    return new Promise(async function (resolve, reject) {
      let res = await us.login(user);
      let {
        code,
        token
      } = res.data;
      if (code) {
        commit('setLoginState', true);
        localStorage.setItem('token', token)
      }
      resolve(code)
    })
  },
  logout({
    commit
  }, that) {
    localStorage.removeItem('token');
    commit('setLoginState', false);
    that.$router.push('/login')
  }
}

export default {
  state,
  mutations,
  actions
}
